<?php

	require '../conn.php';
	$limit = 10;
	$page = 1;
	$type = 0;
	
	if ($_REQUEST['limit'] != '') {
		$limit = $_REQUEST['limit'];
	}
	if ($_REQUEST['page'] != '')
	{
		$page = $_REQUEST['page'];
	}
	if ($_REQUEST['type'] != '')
	{
		$type = $_REQUEST['type'];		
	}
	$query = "SELECT * FROM shop";
	
	if ($type != '' || $_REQUEST['area'] != '' || ($_REQUEST['latitude'] != '' && $_REQUEST['longtitude'] != '') || $_REQUEST['keyword']) {
		$query = $query . ' WHERE ';
	}
	
	if ($type != 0) {
		$query = $query."type=".$type;
	}
	
	if ($_REQUEST['area'] != '') {
		$query = $query." and area_id=".$_REQUEST['area'];
	}
	if ($_REQUEST['latitude'] != '' && $_REQUEST['longtitude'] != '') {
		
		if ($type != '') {
			$query = $query." and ";
		}
		$latitude = $_REQUEST['latitude'];
		$longtitude = $_REQUEST['longtitude'];
		$latitudeDegreePerFiveKilometer = 0.044747572;
		$longtitudeDegreePerFiveKilometer = 0.053763441;
		$minLatitude = $latitude-$latitudeDegreePerFiveKilometer;
		$maxLatitude = $latitude+$latitudeDegreePerFiveKilometer;
		$minLongtitude = $longtitude-$longtitudeDegreePerFiveKilometer;
		$maxLongtitude = $longtitude+$longtitudeDegreePerFiveKilometer;
		$query = $query."latitude>".$minLatitude." and latitude<".$maxLatitude." and longitude>".$minLongtitude." and longitude<".$maxLongtitude;

	}
	
	if ($_REQUEST['keyword'])
	{
		$keyword = $_REQUEST['keyword'];
		if ($type != '') {
			$query = $query." and ";
		}
		
		$query = $query."name LIKE '%".$keyword."%' or title LIKE '%".$keyword."%'";	
	}
	$query = $query." order by shop_id desc limit ".($page - 1)*$limit .", $limit";
	$result = mysql_query($query);
	$arr = array();
	while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
	{
		$shopId = $row['shop_id'];
		$imageQuery = "SELECT * FROM images WHERE shop_id=".$shopId;
		$imageResult = mysql_query($imageQuery);
		$imageArray = array();
		while ($imageRow = mysql_fetch_array($imageResult, MYSQL_ASSOC)) {
			$imageArray[] = $imageRow;
		}
		$row['images'] = $imageArray;
		$arr[] = $row;
	}
	
	$json_str = json_encode($arr);
	echo '{"shops":'.$json_str.'}';

?>
